//
//  ReadCartoonViewController.m
//  Double
//
//  Created by 孟令博 on 15/5/26.
//  Copyright (c) 2015年 袁庆秋. All rights reserved.
//

#import "ReadCartoonViewController.h"
#import "TLTiltSlider.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
enum Direction {
    BEFORE,
    AFTER
};
@interface ReadCartoonViewController ()
@property(nonatomic, retain)UICollectionView *myCollectionView;
@property(nonatomic, retain)NSMutableArray *picArr;
@property(nonatomic, assign)CGFloat picHeight;
@property(nonatomic, retain)UIPageViewController *myPageViewController;
@property(nonatomic, assign)BOOL isChange;
@property(nonatomic, assign)enum Direction direction;
@property(nonatomic, retain)UIActivityIndicatorView *myActivity;
@property(nonatomic, retain)UIView *witeView;
@property(nonatomic, retain)UIImage *myImage;
@property(nonatomic, retain)NSURLResponse *myResponse;
@property(nonatomic, retain)NSMutableData *myData;
@property(nonatomic, retain)UIAlertView *lastAlert;
@property(nonatomic, retain)UIProgressView *myProgress;
@property(nonatomic, retain)NSMutableArray *witeImageArr;
@property(nonatomic, retain)UIImageView *witeImageView;
@property(nonatomic, retain)UILabel *myLabel;
@property(nonatomic, retain)UIView *footView;
@property(nonatomic, assign)BOOL isHidden;
@property(nonatomic, retain)UILabel *indexLabel;
@property(nonatomic, retain)UILabel *countLabel;
@property(nonatomic, retain)UITableView *listTableView;
@property(nonatomic, assign)BOOL isListHidden;
@property(nonatomic, retain)UISlider *lightSlider;
@property(nonatomic, assign)BOOL isNight;
@property (nonatomic, retain) NSArray *bigArray;
@property (nonatomic, retain) TLTiltSlider *slider ;
@property (nonatomic, retain) UIView *headView;
@property (nonatomic, retain) UILabel *uilabel;

@end
@implementation ReadCartoonViewController
- (void)dealloc{
    [_uilabel release];
    [_headView release];
    [_slider release];
    [_myCollectionView release];
    [_picArr release];
    [_myPageViewController release];
    [_bigArray release];
    [_myActivity release];
    [_witeView release];
    [_myImage release];
    [_myData release];
    [_lastAlert release];
    [_myProgress release];
    [_witeImageArr release];
    [_witeImageView release];
    [_myLabel release];
    [_footView release];
    [_indexLabel release];
    [_countLabel release];
    [_listTableView release];
    [_lightSlider release];
    [super dealloc];
    
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.picArr = [NSMutableArray array];
        self.witeImageArr = [NSMutableArray array];
        self.isChange = NO;
        self.isHidden = YES;
        self.isListHidden = YES;
        self.isNight = NO;
        self.bigArray = [NSArray array];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self createData];
    self.view.backgroundColor = [UIColor redColor];
    
    //设置返回按钮
    UIButton *left = [UIButton buttonWithType:UIButtonTypeSystem];
    left.frame = CGRectMake(0, 0, 32, 32);
    [left setImage:[UIImage imageNamed:@"fanhui.png"] forState:UIControlStateNormal];
    [left addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:left];
    self.navigationItem.leftBarButtonItem = leftItem;
    _uilabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 120, 120)];
    _uilabel.center = CGPointMake(WIDTH / 2, HEIGHT / 2);
    _uilabel.backgroundColor = [UIColor colorWithRed:231 green:231 blue:231 alpha:0.5];
    _uilabel.layer.cornerRadius = 20;
    _uilabel.clipsToBounds = YES;
    _uilabel.font = [UIFont systemFontOfSize:40];
    _uilabel.textColor = [UIColor blackColor];
    [_uilabel setTextAlignment:NSTextAlignmentCenter];
    [self createView];

}



- (void)createListTableView{
    //WIDTH / 4    HEIGHT - 270
    //WIDTH / 4   200
    self.listTableView = [[UITableView alloc] initWithFrame:CGRectMake(45, HEIGHT - 262, WIDTH / 4, 200)];
    self.listTableView.delegate = self;
    self.listTableView.dataSource = self;
    self.listTableView.backgroundColor = [UIColor whiteColor];
    self.listTableView.layer.borderWidth = 1.5;
    self.listTableView.layer.cornerRadius = 10;

    self.listTableView.layer.borderColor = [UIColor clearColor].CGColor;
    self.listTableView.alpha = 1;
}
//委托协议的方法
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed
{
    
}

//before
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    return nil;
}
//after
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    return nil;
}
//定义collectionVIew 播放漫画
- (void)createView{
    self.navigationItem.title = self.TiTle;
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake(WIDTH, HEIGHT);
    flow.minimumInteritemSpacing = 0;
    flow.minimumLineSpacing = 0;
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flow];
    [self.view addSubview:self.myCollectionView];
    [self.myCollectionView release];
    [self.myCollectionView registerClass:[PicCartoonCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.myCollectionView.delegate = self;
    self.myCollectionView.dataSource = self;
    self.myCollectionView.pagingEnabled = YES;
    self.myCollectionView.backgroundColor = [UIColor whiteColor];
    
    self.myCollectionView.maximumZoomScale = 2;
    self.myCollectionView.minimumZoomScale = 0.5;
    self.navigationController.navigationBarHidden = YES;
    [[UIApplication sharedApplication] setStatusBarHidden:TRUE];
}

//底部提示lable
- (void)createFootView{
    self.footView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT - 44, WIDTH, 44)];
    [self.view addSubview:self.footView];
    [self.footView release];
    self.footView.backgroundColor = [UIColor grayColor];
    self.footView.alpha = 0.9;
    
    
    self.slider = [[TLTiltSlider alloc] initWithFrame:CGRectMake(10, 5, [UIScreen mainScreen].bounds.size.width - 20, 40)];
        self.slider.value = 0;
        self.slider.minimumValue = 0;
        self.slider.maximumValue = self.picArr.count - 1;
        [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.slider addTarget:self action:@selector(sliderMove:) forControlEvents:UIControlEventValueChanged];
        [self.footView addSubview:_slider];
        [self.slider release];





    
  
}
- (void)sliderAction:(id)sender
{
    NSIndexPath *index = [NSIndexPath indexPathForItem:self.slider.value inSection:0];
    [self.myCollectionView scrollToItemAtIndexPath:index atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    self.navigationItem.title = [NSString stringWithFormat:@"共%ld页", self.picArr.count];

    
}
- (void)sliderMove:(UISlider *)slider
{

    
    


    _uilabel.text = [NSString stringWithFormat:@"%ld", (NSInteger)self.slider.value + 1];
    [self.view addSubview:_uilabel];


}

- (void)lightSliderAction:(UISlider *)slider{
    [UIScreen mainScreen].brightness = slider.value;

}
//返回方法
- (void)leftButtonAction:(UIButton *)button{
    self.tabBarController.tabBar.hidden = YES;
    [self.listTableView removeFromSuperview];
    

    [self.navigationController popViewControllerAnimated:YES];

    
}
#pragma mark - 
#pragma mark cell协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.picArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.isHidden) {
        [self.view bringSubviewToFront:self.footView];
    }
    PicCartoonCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    self.picIndex = indexPath.row + 1;
    self.slider.value = indexPath.row;
    
    self.navigationItem.title = [NSString stringWithFormat:@"共%ld页",self.picArr.count];
    

    //定义手势,显示下面的页数label
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showFootView:)];
    cell.myImageView.userInteractionEnabled = YES;
    [cell.myImageView addGestureRecognizer:tap];
    [tap release];
    [cell.myImageView addSubview:self.picArr[indexPath.row]];
    
    self.navigationController.navigationBarHidden = YES;
    [self.view bringSubviewToFront:self.myCollectionView];
    self.footView.frame = CGRectMake(0, HEIGHT, WIDTH, 100);
    self.isHidden = YES;
    if (!self.isListHidden) {
        [self.listTableView removeFromSuperview];
    }
    [self prefersStatusBarHidden];

    
    return cell;
}

#pragma mark 停止滑动删除label
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self.uilabel removeFromSuperview];
}


- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    _uilabel.text = [NSString stringWithFormat:@"%ld", (NSInteger)self.slider.value + 1];
    [self.view addSubview:_uilabel];

}


- (BOOL)prefersStatusBarHidden
{
    if (self.isHidden) {
        //隐藏
        return YES; // 返回NO表示要显示，返回YES将hiden
    }else{
        return NO;
    }
}

//触摸判断  隐藏底部提示lable
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    if (touch.view.tag == 10086) {
        if (self.isListHidden) {
            [UIView animateWithDuration:0.25 animations:^{
                [self.view addSubview:self.listTableView];
            } completion:^(BOOL finished) {
            }];
            self.isListHidden = NO;
        }else{
            [UIView animateWithDuration:0.25 animations:^{
                [self.listTableView removeFromSuperview];
            } completion:^(BOOL finished) {
            }];
            self.isListHidden = YES;
        }
    }
    

}



//更新页码 翻页时lable上得显示同步
- (void)showFootView:(UITapGestureRecognizer *)tap{
    if (self.isHidden) {
        
        [UIView animateWithDuration:0.25 animations:^{
            self.navigationController.navigationBarHidden = NO;
            [self.view bringSubviewToFront:self.footView];
            
            self.indexLabel.text = [NSString stringWithFormat:@"第 %ld 页",self.picIndex];

            self.footView.frame = CGRectMake(0, HEIGHT - 44, WIDTH, 44);
            self.isHidden = NO;
            [self.view bringSubviewToFront:self.listTableView];
            [self prefersStatusBarHidden];
        } completion:^(BOOL finished) {
        }];
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            self.navigationController.navigationBarHidden = YES;
            [self.view bringSubviewToFront:self.myCollectionView];
            self.footView.frame = CGRectMake(0, HEIGHT, WIDTH, 100);
            self.isHidden = YES;
            if (!self.isListHidden) {
                [self.listTableView removeFromSuperview];
            }
            [self prefersStatusBarHidden];
        } completion:^(BOOL finished) {
        }];
    }
}



- (void)createData{
    NSString *picSTR = [NSString stringWithFormat:@"http://manhua.haomee.cn/?m=Cartoon&ios=23&pad=0&a=getPics&id=%@&uid=(null)",self.comic_id];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:picSTR parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        self.bigArray = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];

        

        for (NSURL *str in self.bigArray) {
            UIImageView *iamgeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            [iamgeView sd_setImageWithURL:str placeholderImage:[UIImage imageNamed:@"placeholder.jpg"] options:SDWebImageRetryFailed];
            
            [self.picArr addObject:iamgeView];
        }

        //根据浏览记录设置偏移量
        self.myCollectionView.contentOffset = CGPointMake(WIDTH * (self.picIndex - 1), 0);
        [self.listTableView reloadData];
        [self createFootView];
        [self.myCollectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
